package com.shiwaixiangcun.customer.pay

import android.app.Activity
import android.text.TextUtils

import com.alipay.sdk.app.PayTask
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent

/**
 * 支付宝支付工具
 *
 * @author Administrator
 */

class AliPay private constructor() {
    val isPay = false

    fun pay(zhiFuBaoResponse: String, mContext: Activity) {
        val payRunnable = Runnable {
            // 构造PayTask 对象
            val aliPay = PayTask(mContext)
            // 调用支付接口，获取支付结果
            val result = aliPay.pay(zhiFuBaoResponse, true)
            val aliResult = AliResult(result)
            val resultStatus = aliResult.resultStatus
            // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
            if (TextUtils.equals(resultStatus, "9000")) {
                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.PAY_SUCCESS, 0))
            } else {
                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.PAY_FAIL, 0))
                // 判断resultStatus 为非“9000”则代表可能支付失败
                // “8000” 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
            }
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    private object AliPayBuilder {
        val Instance = AliPay()
    }

    companion object {

        val instance: AliPay
            get() = AliPayBuilder.Instance
    }

}
